package com.atguigu.tingshu.account.service.impl;

import com.atguigu.tingshu.account.mapper.RechargeInfoMapper;
import com.atguigu.tingshu.account.mapper.UserAccountDetailMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.atguigu.tingshu.vo.account.AccountDeductVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

	@Autowired
	private UserAccountMapper userAccountMapper;
    @Autowired
    private UserAccountDetailMapper userAccountDetailMapper;
	@Autowired
	private RechargeInfoMapper rechargeInfoMapper;

	/**
	 * 保存用户账户
	 * @param map
	 */
	@Override
	public void saveUserAccount(Map<String, Object> map) {
		Long userId = (Long) map.get("userId");
		BigDecimal amount = (BigDecimal) map.get("amount");
		UserAccount userAccount = new UserAccount();
		userAccount.setUserId(userId);
		userAccount.setTotalAmount(amount);
		userAccount.setLockAmount(BigDecimal.ZERO);
		userAccount.setAvailableAmount(amount);
		userAccount.setTotalIncomeAmount(amount);
		userAccount.setTotalPayAmount(BigDecimal.ZERO);
		int rows = userAccountMapper.insert(userAccount);
		if (rows > 0) {
			String title = (String) map.get("title");
			String orderNo = (String) map.get("orderNo");
			//2.保存账户变动日志
			this.saveUserAccountDetail(userId, title, SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT, amount, orderNo);
		}

	}

	/**
	 * 保存用户账户明细
	 */
	@Override
	public void saveUserAccountDetail(Long userId, String title,String tradeType,  BigDecimal amount, String orderNo) {
		UserAccountDetail userAccountDetail = new UserAccountDetail();
		userAccountDetail.setUserId(userId);
		userAccountDetail.setTitle(title);
		userAccountDetail.setTradeType(tradeType);
		userAccountDetail.setAmount(amount);
		userAccountDetail.setOrderNo(orderNo);
		userAccountDetailMapper.insert(userAccountDetail);
	}

	/**
	 * 获取用户账户可用余额
	 * @param userId
	 * @return
	 */
	@Override
	public BigDecimal getAvailableAmount(Long userId) {
		UserAccount userAccount = userAccountMapper.selectOne(new LambdaQueryWrapper<UserAccount>()
				.eq(UserAccount::getUserId, userId)
				.select(UserAccount::getAvailableAmount));
		if (userAccount != null) {
			return userAccount.getAvailableAmount();
		}
		return null;
	}

	/**
	 * 检查扣减账户余额
	 *
	 * @param accountDeductVo
	 */
	@Override
	public void checkAndDeduct(AccountDeductVo accountDeductVo) {
		//1.检查余额是否满足扣减条件，采用数据库"锁机制"悲观锁，解决并发问题
		UserAccount userAccount = userAccountMapper.checkDeduction(accountDeductVo.getUserId(), accountDeductVo.getAmount());
		if (userAccount == null) {
			throw new RuntimeException("账户余额不足！");
		}
		//2.如果满足扣减条件，扣减账户余额
		int rows = userAccountMapper.update(null,
				new LambdaUpdateWrapper<UserAccount>()
						.eq(UserAccount::getUserId, accountDeductVo.getUserId())
						.setSql("total_amount = total_amount - " + accountDeductVo.getAmount())
						.setSql("available_amount = available_amount - " + accountDeductVo.getAmount())
						.setSql("total_pay_amount = total_pay_amount + " + accountDeductVo.getAmount())
		);
		if (rows == 0) {
			throw new RuntimeException("账户余额不足！");
		}
		//3.保存账户变动日志
		this.saveUserAccountDetail(accountDeductVo.getUserId(), accountDeductVo.getContent(), SystemConstant.ACCOUNT_TRADE_TYPE_MINUS, accountDeductVo.getAmount(), accountDeductVo.getOrderNo());
	}

	/**
	 * 用户充值或消费记录分页列表
	 * @param pageInfo
	 * @param userId
	 * @return
	 */
	@Override
	public void findUserRechargeOrConsumePage(Page<UserAccountDetail> pageInfo, String tradeType, Long userId) {
		LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<UserAccountDetail>()
				.eq(UserAccountDetail::getUserId, userId)
				.eq(UserAccountDetail::getTradeType, tradeType)
				.orderByDesc(UserAccountDetail::getCreateTime);
		userAccountDetailMapper.selectPage(pageInfo, queryWrapper);
	}
}
